import frappe
from frappe import _
from frappe.utils import flt
from erpnext.manufacturing.doctype.bom.bom import BOM
from light_mes.light_mes.doctype.subcontracting_service_price.subcontracting_service_price import get_subcontracting_price

class CustomBOM(BOM):
    @frappe.whitelist()
    def get_routing(self):
        """重写获取工艺路线方法，增加自定义字段并计算委外单价"""
        if self.routing:
            self.set("operations", [])
            fields = [
                "sequence_id",
                "operation",
                "workstation",
                "workstation_type", 
                "description",
                "time_in_mins",
                "batch_size",
                "operating_cost",
                "idx",
                "hour_rate",
                "set_cost_based_on_bom_qty",
                "fixed_time",
                # 添加自定义字段
                "custom_is_subcontracting",
                "custom_enable_wip_receipt",
                "custom_supplier",
                "custom_service_price"
            ]

            for row in frappe.get_all(
                "BOM Operation",
                fields=fields,
                filters={"parenttype": "Routing", "parent": self.routing},
                order_by="sequence_id, idx",
            ):
                child = self.append("operations", row)
                child.hour_rate = flt(row.hour_rate / self.conversion_rate, child.precision("hour_rate"))
            
            # 在获取完工艺路线后计算委外单价、获取税率、计算含税价
            self.calculate_subcontracting_prices()
    
    def calculate_subcontracting_prices(self):
        """为所有工序计算委外单价、税率、含税价"""
        if not self.company or not self.item or not self.quantity:
            return
        
        # 获取Light Mes Settings 中设置的税率
        tax_rate = frappe.db.get_single_value("Light Mes Settings", "tax_rate")
        
            
        for operation in self.operations:
            # 如果工序有供应商，计算委外单价
            if operation.custom_supplier:
                price = get_subcontracting_price(
                    company=self.company,
                    supplier=operation.custom_supplier,
                    qty=self.quantity,
                    item_code=self.item,
                    operation=operation.operation
                )
                
                # 更新工序的委外单价
                operation.custom_service_price = price
                operation.custom_tax_rate = tax_rate
                operation.custom_service_price_with_tax = flt(price * (1 + tax_rate / 100), operation.precision("custom_service_price_with_tax"))